<route lang="jsonc" type="page">
  {
    "layout": "tabbar",
    "style": {
      "navigationStyle": "custom",
      "navigationBarTitleText": "工单"
    }
  }
</route>

<script lang="ts" setup>
import SarTag from 'sard-uniapp/components/tag/tag.vue'
import ScrollSpy from 'sard-uniapp/components/scroll-spy/scroll-spy.vue'
import PullDownRefresh from 'sard-uniapp/components/pull-down-refresh/pull-down-refresh.vue'
import { getDictByType } from '@/api/common'
import { getOrderList, } from '@/api/order'
import { getItemStatusDetail } from '@/pages/order/dataHandler'
import DiaOrderDetail from './components/DiaOrderDetail.vue'
import PopCompleteUpload from './components/PopCompleteUpload.vue'
import { useToast } from 'wot-design-uni'
import type { LoadMoreState } from 'wot-design-uni/components/wd-loadmore/types'
import {useGetOrderStatusActions} from '@/pages/order/dataHandler'

const toast = useToast()
const activeTab = ref('all')
const fetchState = ref<LoadMoreState>('loading')
const loading = ref(false)
const totalCount = ref(0)
const queryParam = reactive({
  pageNo: 1,
  pageSize: 10
})
const dictLib = reactive({
  order_status: [], // 工单状态
})
const tableData = ref([])
const dia_order_detail = ref()
const complete_upload = ref()
const emptyInfo = computed(() => {
  const image = activeTab.value ? 'search' : 'content'
  const tip = activeTab.value ? '未查询到当前选项工单' : '暂无工单'
  return {
    image,
    tip,
  }
})
const getDictLib = async () => {
  const dictTypeArr = Object.keys(dictLib)
  const dictPromises = dictTypeArr.map((dictType) =>
    getDictByType({ dictType })
  )
  const res = await Promise.all(dictPromises)
  res.forEach((result, index) => {
    const dict = dictTypeArr[index]
    dictLib[dict] = result
  })
  dictLib.order_status.some((item) => {
    if (item.value === 'ASSIGNED') {
      item.label = '待处理'
      return true
    }
    return false
  })
}
const orderOptions = computed(() => {
  const options = dictLib.order_status.filter((ele) => ele.value !== 'CANCELED')
  return [{ label: '全部', value: 'all' }, ...options]
})
/**
 * type: regular | refresh | loadMore
 */
const _getOrderList = async (type = 'regular') => {
  loading.value = true
  if (type === 'refresh') {
    queryParam.pageNo = 1
    tableData.value = []
    fetchState.value = 'loading'
  }
  if (fetchState.value === 'finished') {
    loading.value = false
    return
  }
  if (type === 'loadMore') {
    queryParam.pageNo += 1
  }
  try {
    const res = await getOrderList({
      ...queryParam,
      status: activeTab.value === 'all' ? '' : activeTab.value,
    })
    if (res.code === 0) {
      const { list, total } = res.data
      list?.forEach((item) => {
        const { problemPhotoUrl } = item
        if (problemPhotoUrl) {
          const imgArr = problemPhotoUrl.split(',')
          item.firstImg = imgArr[0]
          item.noImg = false
          item.imgArr = imgArr
        } else {
          item.noImg = true
          item.firstImg = ''
          item.imgArr = []
        }
        getItemStatusDetail(item)
      })
      totalCount.value = total
      const arr = list
      // .concat(list)
      // .concat(list)
      // .concat(list)
      // .concat(list)
      // .concat(list)
      // if (type === 'refresh') {
      //   tableData.value = [...(arr ?? [])]
      // } else {
        tableData.value = [...tableData.value, ...(arr ?? [])]
      // }
      if (tableData.value.length >= total) {
        fetchState.value = 'finished'
      }
    } else {
      fetchState.value = 'error'
    }
  } finally {
    loading.value = false
  }
}

const changeStatus = (val: any) => {
  activeTab.value = val.name
  _getOrderList('refresh')
}
const handleCheckDetail = (item) => {
  dia_order_detail.value.open(item)
}
const statusActions = useGetOrderStatusActions({successFn:()=>{
  _getOrderList('refresh')
  setTimeout(() => {
    dia_order_detail.value.close()
  }, 500)
}})
const handleTypeDeal = (item) => {
  const { status } = item
  if (status === 'ASSIGNED') {
    // 出发
    statusActions.handleSetOff(item)
  } else if (status === 'START') {
    statusActions.handleSignIn(item)
  } else if (status === 'ARRIVED') {
    statusActions.handleStartRepair(item)
  } else if (status === 'REPAIRING') {
    complete_upload.value.open(item)
    // handleComplete(item)
  } else if (status === 'COMPLETED') {
    // handleComplete(item)
  }
}
const pull_down_refresh = ref()
const onScroll = (event: any) => {
  pull_down_refresh.value?.enableToRefresh(event.detail.scrollTop === 0)
}
const onScrolltoupper = () => {
  pull_down_refresh.value?.enableToRefresh(true)
}
onShow(() => {
  _getOrderList()
})

onLoad(() => {
  getDictLib()
})
// onPullDownRefresh(async () => {
//   try {
//     await _getOrderList('refresh')
//   } finally {
//     uni.stopPullDownRefresh();
//   }
// });
</script>

<template>
  <view class="bg-main h-full flex flex-col">
    <wd-navbar title="工单" />
    <wd-tabs v-model="activeTab" slidable="always" @change="changeStatus">
      <wd-tab
        v-for="rItem in orderOptions"
        :key="rItem.value"
        :title="rItem.label"
        :name="rItem.value"
      />
    </wd-tabs>
    <view class="orderListWrap">
      <scroll-spy
        root-style="height: 100%;"
        @scrolltolower="_getOrderList('loadMore')"
        @scroll="onScroll"
        @scrolltoupper="onScrolltoupper"
      >
        <PullDownRefresh
          ref="pull_down_refresh"
          :loading="loading"
          @refresh="_getOrderList('refresh')"
        >
          <template v-if="tableData.length">
            <wd-card v-for="item in tableData" :key="item.orderId">
              <view class="pt-3">
                <view class="mb-2 flex items-center justify-between">
                  <text class="text-title font-bold">
                    {{ item.requestTitle }}
                  </text>
                  <sar-tag
                    :color="item.status_label_bg"
                    :text-color="item.status_label_color"
                  >
                    {{ item.status_label }}
                  </sar-tag>
                </view>
                <view class="flex gap-3">
                  <JediImg
                    :width="80"
                    :height="80"
                    :src="item.firstImg"
                    mode="aspectFit"
                    class="shrink-0 border border-solid border-gray-100 rounded"
                  />
                  <view class="flex flex-col">
                    <view class="flex">
                      <i class="iconfont icon-part-type text-sub mr-2" />
                      <text class="text-normal">
                        {{ item.repairCategory }}
                      </text>
                    </view>
                    <view class="flex">
                      <i class="iconfont icon-clock text-sub mr-2" />
                      <text class="text-normal">
                        {{ item.status_time_label }}：{{ item.status_time }}
                      </text>
                    </view>
                    <view class="flex">
                      <i class="iconfont icon-locate-line text-sub mr-2" />
                      <text class="text-normal">
                        {{ item.stationLocation }}
                      </text>
                    </view>
                  </view>
                </view>
              </view>
              <template #footer>
                <view class="flex justify-between items-center">
                  <text class="text-left text-sub text-xs">距目的地{{ item.distance }}公里</text>
                  <view class="flex">
                    <wd-button
                      plain
                      type="primary"
                      @click="handleCheckDetail(item)"
                    >
                      <i class="iconfont icon-eye inline text-base" />
                      详情
                    </wd-button>
                    <wd-button
                      v-if="item.status_btn_visible"
                      :type="item.status_btn_type"
                      @click="handleTypeDeal(item)"
                    >
                      <i :class="`inline iconfont ${item.status_icon} text-base`" />
                      {{ item.status_btn_text }}
                    </wd-button>
                  </view>
                </view>
              </template>
            </wd-card>
          </template>
          <JediEmpty  v-if="!tableData.length && !loading" :image="emptyInfo.image" :tip="emptyInfo.tip" />
          <wd-loadmore
            v-if="tableData.length && totalCount > 3"
            :state="fetchState"
            finished-text="已全部加载"
            @reload="_getOrderList"
          />
        </PullDownRefresh>
      </scroll-spy>
    </view>
    <DiaOrderDetail
      ref="dia_order_detail"
      @refresh="_getOrderList('refresh')"
    />
    <PopCompleteUpload
      ref="complete_upload"
      @refresh="_getOrderList('refresh')"
    />
  </view>
</template>

<style lang="scss">
.orderListWrap {
  flex: 1;
  height: 100px;
  // overflow-y: auto;
  margin-top: 6px;
  // &.weixinDeal {
  //   padding-bottom: 80px;
  // }
  .wd-card {
    margin-right: 8px !important;
    margin-left: 8px !important;
  }
}
</style>
